package com.qire.manhua.dialog;

import android.content.Context;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;

import com.qire.antsrouter.AntsRouter;
import com.qire.common.basic.DateUtil;
import com.qire.common.basic.StringUtil;
import com.qire.common.constant.CacheStorageKey;
import com.qire.common.constant.Navigation;
import com.qire.common.model.entity.UserEntity;
import com.qire.common.support.base.BaseDialog;
import com.qire.common.utils.CacheStorageUtil;
import com.qire.manhua.R;
import com.qire.manhua.databinding.DialogMemberOverduePromptBinding;

import java.util.concurrent.TimeUnit;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

public class MemberOverduePromptDialog extends BaseDialog {

    /** 显示过期提示dialog如果满足提示需求 */
    public static void showIfNeedTips(Context context) {
        /***************************************************************************************************
         * 1.获得VIP过期时间
         * 2.获得上次提示时间
         * 3.计算上次一提示过期时剩余时间
         * 4.计算今天到过期时剩余时间
         * 5.定义过期提示表。
         * 6.循环排除上次提示过的过期时间段
         * 7.判断符合今天剩余时间的提示要求并显示弹窗
         ***************************************************************************************************/
        String vipExpirationTime = UserEntity.self.getVipExpirationTime();//"2021-03-29 12:50:00";//
        if(StringUtil.isEmpty(vipExpirationTime)) {
            return;
        }

        // TODO 切换账号后过期时间相同
        String lastTipsTime = CacheStorageUtil.queryString(CacheStorageKey.MEMBER_OVERDUE_PROMPT, "");//"2021-03-22 12:49:00"; //

        // 过期时间精确到分钟，与服务器同步
        long lastRemainingMinutes;
        if(StringUtil.isEmpty(lastTipsTime)) {
            lastRemainingMinutes = toMinutes(365);
        } else {
            lastRemainingMinutes = DateUtil.yMdHms.fromTo(lastTipsTime, vipExpirationTime, false).formatBy(TimeUnit.MILLISECONDS::toMinutes);
        }

        long remainingMinutes = DateUtil.yMdHms.toSomeday(vipExpirationTime, false).formatBy(TimeUnit.MILLISECONDS::toMinutes);

        long[] tipsMinutesArray = {toMinutes(7), toMinutes(3), toMinutes(1), toMinutes(0), toMinutes(-365)};

        for(int index = 0; index < tipsMinutesArray.length; index++) {
            long tipsMinutes = tipsMinutesArray[index];
            long tipsLastMinutes = index == 0 ? Long.MAX_VALUE : tipsMinutesArray[index - 1];

            if(range(lastRemainingMinutes, tipsLastMinutes, tipsMinutes)) {
                continue;
            }

            if(range(remainingMinutes, tipsLastMinutes, tipsMinutes)) {
                new MemberOverduePromptDialog(context)
                        .setOverdueTips(remainingMinutes, vipExpirationTime)
                        .show();
                CacheStorageUtil.saveIfNotExist(CacheStorageKey.MEMBER_OVERDUE_PROMPT, DateUtil.yMdHms.currentTime());
                return;
            }
        }
    }

    private static boolean range(long minutes, long beginMinutes, long endMinutes) {
        return beginMinutes >= minutes && minutes >= endMinutes;
    }

    /**
     * 天数转分钟
     * @param days 几天
     * @return
     */
    private static long toMinutes(long days) {
        return TimeUnit.DAYS.toMinutes(days);
    }

    /**
     * 分钟转天数
     * @param minutes 几分钟
     * @return
     */
    private static long toDays(long minutes) {
//        long oneDayMinutes = TimeUnit.DAYS.toMinutes(1);
//        long remainder = minutes % oneDayMinutes;
//
//        minutes = minutes - (remainder) ;
        return TimeUnit.MINUTES.toDays(minutes);
    }

    /*********************************************************************************************************************/

    public final ObservableField<CharSequence> overdueTips = new ObservableField<>();
    public final ObservableField<CharSequence> validityPeriod = new ObservableField<>();

    private final DialogMemberOverduePromptBinding viewDataBinder;

    private MemberOverduePromptDialog(@NonNull Context context) {
        super(context, R.style.CustomDialog_Translucent);
        viewDataBinder = DialogMemberOverduePromptBinding.inflate(LayoutInflater.from(context));
        viewDataBinder.setMemberOverduePromptDialog(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(viewDataBinder.getRoot());
    }

    private MemberOverduePromptDialog setOverdueTips(long remainingMinutes, String vipExpirationTime) {
        CharSequence overdueTips;
        CharSequence validityPeriod;
        if(remainingMinutes >= 0) {
            overdueTips = remainingMinutes <= toMinutes(1)
                    ? "您的VIP特权马上就要过期了"
                    : Html.fromHtml(String.format("您的VIP特权将于<font color=#ff9204>%d天</font>后过期", toDays(remainingMinutes)));
            validityPeriod = "有效期至：" + vipExpirationTime;
        } else {
            overdueTips = "亲，您的VIP已经过期";
            validityPeriod = "";
        }

        this.overdueTips.set(overdueTips);
        this.validityPeriod.set(validityPeriod);
        return this;
    }

    public void renewalBtnOnClick(View view) {
        AntsRouter.ROUTER.buildCard(Navigation.Page.BuyMembershipPage).navigation();
    }

    public void closeBtnOnClick(View view) {
        dismiss();
    }

}
